<?php
// 应用公共文件

use think\Paginator;
use think\facade\App;
use app\admin\model\SystemConfig;
use app\admin\model\WxConfig;
use app\admin\model\SystemLog;

// 引入图鸟文件
require \think\facade\App::getRootPath() . "app/common/tuniao.php";

/**
 * 类型
 * @return int
 */
function tn_type(): int
{
    return 1;
}

/**
 * 判断是否为json格式的字符串
 * @param $string
 * @return bool
 */
function is_json($string)
{
    json_decode($string);

    return (json_last_error() === JSON_ERROR_NONE);
}

/**
 * 将中文的逗号转换成英文的逗号
 * @param string $rawString
 * @return string|string[]
 */
function convert_chinese_dot(string $rawString)
{
    return str_replace('，',',',$rawString);
}

/**
 * 去除xss代码
 * @param string $content
 * @return string
 */
function remove_xss(string $content)
{
//    $cfg = Config::get('purifier');
//    $config = \HTMLPurifier_HTML5Config::create($cfg);
//    $purifier = new \HTMLPurifier($config);
//    return $purifier->purify($content);

    if (empty($content)) {
        return '';
    }

    $content = str_replace('&lt;','<',$content);
    $content = str_replace('&gt;','>',$content);
//    $content = strip_tags($content, '<img><p><b><i><a><strike><pre><code><font><blockquote><span><ul><li><table><tbody><tr><td><ol><iframe><embed><h1><h2><h3><h4><h5><h6>');
    $content = preg_replace('/([\x00-\x08|\x0b-\x0c|\x0e-\x19])/', '', $content);
    $search = 'abcdefghijklmnopqrstuvwxyz';
    $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $search .= '1234567890!@#$%^&*()';
    $search .= ',~`";:?+/={}[]-_|\'\\';
    for ($i = 0; $i < strlen($search); $i++) {
        $content = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $content);
        $content = preg_replace('/(�{0,8}'.ord($search[$i]).';?)/', $search[$i], $content);
    }
    $ra1 = array('expression', 'applet', 'meta', 'xml', 'blink', 'link', 'object', 'frameset', 'bgsound', 'title', 'base');
    $ra2 = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
    $ra = array_merge($ra1, $ra2);
    $found = true;
    while ($found == true) {
        $content_before = $content;
        for ($i = 0; $i < sizeof($ra); $i++) {
            $pattern = '/';
            for ($j = 0; $j < strlen($ra[$i]); $j++) {
                if ($j > 0) {
                    $pattern .= '(';
                    $pattern .= '(&#[xX]0{0,8}([9ab]);)';
                    $pattern .= '|';
                    $pattern .= '|(�{0,8}([9|10|13]);)';
                    $pattern .= ')*';
                }
                $pattern .= $ra[$i][$j];
            }
            $pattern .= '/i';
            $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2);
            $content = preg_replace($pattern, $replacement, $content);
            if ($content_before == $content) {
                $found = false;
            }
        }
    }
    return $content;

}

/**
 * 根据传入的文件大小返回对应的带单位的文件大小
 * @param int $size
 * @return string
 */
function format_bytes(int $size): string
{
    $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
    $i = 0;
    for (; $size >= 1024 && $i < 5; $i++) {
        $size /= 1024;
    }

    return (string)(round($size, 2) . $units[$i]);
}

/**
 * 返回vue-element-admin分页所需格式的数据
 * @param Paginator $paginate 分页对象
 * @param bool $is_page 是否需要分页
 * @return array
 */
function return_vue_element_admin_pagination_data(Paginator $paginate, bool $is_page = true)
{
    $data = $paginate->toArray();

    $page_data = [];

    if ($is_page) {
        $page_data['total'] = $data['total'];

        // 判断是否为空
        if (empty($data['data'])) {
            $page_data['data'] = [];
        } else {
            $page_data['data'] = $data['data'];
        }
    } else {
        $page_data['data'] = $data['data'];
    }

    return $page_data;
}

/**
 * 删除upload上传的文件
 * @param $file_path
 */
function delFile($file_path)
{
    if (!empty($file_path)) {
        $delete_path = [];
        if (!is_array($file_path)) {
            $delete_path[] = $file_path;
        } else {
            $delete_path = $file_path;
        }
        foreach ($delete_path as $item) {
            $item = remove_url_prefix($item);
            $file_name = App::getRootPath() . 'public' . $item;
            if (file_exists($file_name)){
                unlink($file_name);
            }
        }

    }
}

/**
 * 去除传入字符串中的域名信息
 * @param $data
 * @return mixed
 */
function remove_url_prefix(string $data)
{
    preg_match('/^https?:\/\/[\w-]+(\.[\w-]+){0,}/', $data, $match_data);
    if (!empty($match_data[0])) {
        $data = str_replace($match_data[0], '', $data);
    }

    return $data;
}

/**
 * 为图片添加域名前缀
 * @param $imgUrl
 * @return string
 */
function add_image_prefix(string $imgUrl)
{
    return get_system_config('site_url') . $imgUrl;
}

/**
 * 获取对应字段配置的值
 * @param string $en_name
 * @param string $default
 * @return mixed|string
 */
function get_system_config(string $en_name, $default = '')
{
    return SystemConfig::getConfigValue($en_name, $default);
}

/**
 * 获取微信对应字段配置的值
 * @param string $en_name
 * @param string $default
 * @return mixed|string
 */
function get_wx_config(string $en_name, $default = '')
{
    return WxConfig::getConfigValue($en_name, $default);
}

/**
 * 写入系统日志
 * @param string $content
 * @param string $user_name
 * @param string $controller
 * @param string $action
 */
function write_system_log(string $content = '', string $user_name = '', string $controller = '', string $action = '')
{
    (new SystemLog())->writeSystemLog($content, $user_name, $controller, $action);
}

/**
 * 获取指定长度的随机字符串
 * @param $length
 * @return string|null
 */
function get_rand_char($length)
{
    $str = null;
    $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    $max = strlen($strPol) - 1;

    for ($i = 0; $i < $length; $i++){
        $str .= $strPol[rand(0,$max)];
    }

    return $str;
}


/**
 * 检查当前的PHP版本是否符合要求
 * @param $need_version
 * @return bool
 */
function check_php_version($need_version)
{
    // 获取PHP版本号第一位
    $first_version = substr(PHP_VERSION,0,1);
    // 获取PHP版本号第二位
    $second_version = substr(PHP_VERSION,2,1);

    // 获取需要的PHP版本号第一位
    $first_need = substr($need_version,0,1);
    // 获取需要的PHP版本号第二位
    $second_need = substr($need_version,2,1);

    if ($first_version < $first_need && $second_version < $second_need) {
        return false;
    }

    return true;
}

//获取网络数据
/**
 * post传输，json格式的数据
 * @param string $url post请求地址
 * @param array $params 传输的数据
 * @return mixed
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\DbException
 * @throws \think\db\exception\ModelNotFoundException
 */
function curl_post($url, array $params = array())
{
    $data_string = json_encode($params);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_POST, 1);
    if (get_system_config('site_https_on')){
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,true);
    }else{
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
    }
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt(
        $ch, CURLOPT_HTTPHEADER,
        array(
            'Content-Type: application/json'
        )
    );
    $data = curl_exec($ch);
    curl_close($ch);
    return ($data);
}

/**
 * post传输，text格式的数据
 * @param $url post请求地址
 * @param $rawData 传输的数据
 * @return bool|string
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\DbException
 * @throws \think\db\exception\ModelNotFoundException
 */
function curl_post_raw($url, $rawData)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_POST, 1);
    if (get_system_config('site_https_on')){
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,true);
    }else{
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
    }
    curl_setopt($ch, CURLOPT_POSTFIELDS, $rawData);
    curl_setopt(
        $ch, CURLOPT_HTTPHEADER,
        array(
            'Content-Type: text'
        )
    );
    $data = curl_exec($ch);
    curl_close($ch);
    return ($data);
}

/**
 * 发送http get请求获取内容
 * @param string $url get请求地址
 * @param int $httpCode 返回状态码
 * @return mixed
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\DbException
 * @throws \think\db\exception\ModelNotFoundException
 */
function curl_get($url,&$httpCode = 0)
{
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);

    //不做证书校验，如果部署在linux下请改为true
    if (get_system_config('https_on')){
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,true);
    }else{
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
    }

    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,10);

    $file_contents = curl_exec($ch);
    $httpCode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
    curl_close($ch);

    return $file_contents;

}

